import React, { useEffect, useRef, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { Card, Breadcrumb, Form, Input, Select, Button, Space, Radio, Upload, Modal, message } from 'antd'
import { useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'
import { getChannelList } from 'store/action/article'
import ReactQuill from 'react-quill'
import styles from './index.module.scss'
import 'react-quill/dist/quill.snow.css'
import { PlusOutlined } from '@ant-design/icons'
import { saveArticle, getArticleInfo,editArticle } from 'store/action/article'
export default function ArticlePublish() {
  const [type, setType] = useState(1)
  const navigate = useNavigate()
  const formRef = useRef(null)

  const params1 = useParams()
  const isEdit = params1.id !== undefined
  const [fileList, setFileList] = useState([
    {
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    }
  ])
  const fileRef = useRef(fileList)
  const [isVisible, setIsVisible] = useState(false)
  const [preview, setPreview] = useState('')
  //修改上面图片数量按钮
  const onTypeChange = (e) => {
    console.log('e', e.target.value);
    setType(e.target.value)
    setFileList([])
  }
  //上传图片
  const onChange = ({ fileList }) => {
    setFileList(fileList)
  }
  //图片预览
  const onPreview = (file) => {
    console.log(file)
    setIsVisible(true)
    setPreview(file.url || file.response.data.url)
  }
  const channels = useSelector((state) => state.article.channels)
  const dispatch = useDispatch()
  const beforeUpload = (file) => {
    console.log('file1', file);
    // if(file.size>=1024*500){
    //   message.warn('上传的文件不能超过500KB')
    //   return Upload.LIST_IGNORE
    // }
    // if(!['images/png','images/jpeg'].includes(file.type)){
    //   message.warn('只能上传jpeg和png的图片')
    //   return Upload.LIST_IGNORE
    // }
    return true
  }

  useEffect(() => {
    dispatch(getChannelList())
  }, [dispatch])
  // 获取文章详情
  useEffect(() => {
    if (!params1.id) return
    // 如果有id，代表是修改
    dispatch(getArticleInfo(params1.id)).then((res) => {
      // 表单的回显
      formRef.current.setFieldsValue({
        ...res,
        type: res.cover.type
      })
      // 图片的回显
      setType(res.cover.type)
      const list = res.cover.images.map((item) => {
        return {
          url: item
        }
      })
      setFileList(list)
      fileRef.current = list
    })
  }, [params1.id, dispatch])

  const onFinish = async (values) => {
    add(values, false)
  }

  //草稿
  const add = async (values, draft) => {
    const images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })
    const data = {
      ...values,
      cover: {
        type: type,
        images: images
      },

    }
    if (params1.id) {
      // 修改
      await dispatch(
        editArticle(draft, {
          ...data,
          id:params1.id
        })
      )
    } else {
      // 新增
      await dispatch(saveArticle(data,draft))
    }
    message.success('添加文章成功')
    navigate('/home/list')
  }



  const addDraft = async () => {
    console.log('添加草稿');
    const values = await formRef.current.validateFields()
    console.log('values', values);
    add(values, true)

  }
  return (
    <div className={styles.root}>
      <Card title={<Breadcrumb separator=">" >
        <Modal
          width={800}
          title="图片预览"
          visible={isVisible}
          footer={null}
          onCancel={() => setIsVisible(false)}
        >
          <div style={{ textAlign: 'center' }}>
            <img src={preview} style={{ width: 600 }} alt="" />
          </div>
        </Modal>
        <Breadcrumb.Item>
          <Link to="/home">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>发布文章</Breadcrumb.Item>
      </Breadcrumb>}>

        <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} size="large"
          onFinish={onFinish}
          initialValues={{ content: '', type: 0 }} ref={formRef}>
          <Form.Item label="标题" name="title" rules={[
            {
              required: true,
              message: '文章的标题不能为空'
            }
          ]}>
            <Input
              placeholder="请输入文章的标题"
              style={{ width: 400 }}

            ></Input>
          </Form.Item>
          <Form.Item label="频道" name="channel_id" rules={[{ required: true, message: '请选择频道' }]}>
            <Select style={{ width: 200 }} allowClear placeholder="请选择频道">
              {channels.map((item) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            {type !== 0 && (
              //fileList用来控制文件列表
              <Upload listType="picture-card" fileList={fileList} action="http://geek.itheima.net/v1_0/upload"
                name="image" onChange={onChange} onPreview={onPreview}
                beforeUpload={beforeUpload}>
                {fileList.length < type && <PlusOutlined />}
              </Upload>
            )}
          </Form.Item>
          <Form.Item label="内容" name="content">
            <ReactQuill theme='snow' placeholder='请输入文章的内容'></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType='submit'>发布文章</Button>
              <Button onClick={addDraft} >存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}